<?php

namespace seecms\lib\response;

use seecms\SeeLang;
use seecms\SeeResponse;
use magein\utils\Result;

class JsonResponse extends SeeResponse
{
    public function __construct($data, int $status_code = 200)
    {
        parent::__construct($data, 'json', $status_code);
    }

    /**
     * @param $message
     * @param int $code
     * @param $data
     * @return JsonResponse
     */
    public static function error($message, int $code = 1, $data = null): JsonResponse
    {
        $data = [
            'code' => $code,
            'msg' => $message,
            'data' => $data,
        ];

        return new self($data);
    }

    /**
     * @param $data
     * @param string $message
     * @param int $code
     * @return JsonResponse
     */
    public static function success($data = null, string $message = null, int $code = 0): JsonResponse
    {
        $data = [
            'code' => $code,
            'msg' => $message,
            'data' => $data,
        ];

        return new self($data);
    }

    /**
     * @param Result|mixed $result
     * @return JsonResponse
     */
    public static function result($result): JsonResponse
    {
        if ($result === '' || $result === false || $result === null) {
            return self::error(SeeLang::operate('update_fail'));
        }

        if ($result instanceof Result) {
            return new self([
                'code' => $result->getCode(),
                'msg' => $result->getMsg(),
                'data' => $result->getData(),
            ]);
        }

        return self::success($result, SeeLang::operate('update_success'));
    }

    public function toString()
    {
        return $this->data ? json_encode($this->data) : '';
    }
}